package hbbft

import (
	"math/big"

	"go.dedis.ch/kyber/v3"
	"go.dedis.ch/kyber/v3/share"
)

// 使用crypto_real_impl.go中定义的suite
func getSuite() kyber.Group {
	return suite
}

// kyberToTPKEPublicKey 将kyber的PubPoly适配为TPKEPublicKey
// 注意：这是简化的适配器，实际使用中需要根据kyber的PubPoly API完善
func kyberToTPKEPublicKey(pubPoly *share.PubPoly, N, T int) *TPKEPublicKey {
	if pubPoly == nil {
		return nil
	}
	
	// 简化实现：创建占位符TPKEPublicKey
	s := getSuite()
	base := s.Point().Base()
	
	VK := &Point{
		X: pointToBigInt(base),
		Y: big.NewInt(0),
	}
	
	VKs := make([]*Point, N)
	for i := 0; i < N; i++ {
		// 临时：使用基础点，实际应该评估pubPoly.Eval(i+1)
		VKs[i] = &Point{
			X: pointToBigInt(base),
			Y: big.NewInt(0),
		}
	}
	
	return &TPKEPublicKey{
		N:   N,
		K:   T,
		VK:  VK,
		VKs: VKs,
	}
}

// kyberToTPKEPrivateKey 将kyber的PriShare适配为TPKEPrivateKey
func kyberToTPKEPrivateKey(privShare *share.PriShare, pubKey *TPKEPublicKey) *TPKEPrivateKey {
	if privShare == nil || pubKey == nil {
		return nil
	}
	
	return &TPKEPrivateKey{
		TPKEPublicKey: pubKey,
		I:             privShare.I,
		SK:            scalarToBigInt(privShare.V),
	}
}

// kyberToTBLSPublicKey 将kyber的PubPoly适配为TBLSPublicKey
func kyberToTBLSPublicKey(pubPoly *share.PubPoly, N, T int) *TBLSPublicKey {
	if pubPoly == nil {
		return nil
	}
	
	// 简化实现：类似于TPKE
	s := getSuite()
	base := s.Point().Base()
	
	VK := &Point{
		X: pointToBigInt(base),
		Y: big.NewInt(0),
	}
	
	VKs := make([]*Point, N)
	for i := 0; i < N; i++ {
		VKs[i] = &Point{
			X: pointToBigInt(base),
			Y: big.NewInt(0),
		}
	}
	
	return &TBLSPublicKey{
		N:   N,
		K:   T,
		VK:  VK,
		VKs: VKs,
	}
}

// kyberToTBLSPrivateKey 将kyber的PriShare适配为TBLSPrivateKey
func kyberToTBLSPrivateKey(privShare *share.PriShare, pubKey *TBLSPublicKey) *TBLSPrivateKey {
	if privShare == nil || pubKey == nil {
		return nil
	}
	
	return &TBLSPrivateKey{
		TBLSPublicKey: pubKey,
		I:             privShare.I,
		SK:            scalarToBigInt(privShare.V),
	}
}

// pointToBigInt 将kyber Point转换为big.Int（简化处理）
func pointToBigInt(p kyber.Point) *big.Int {
	if p == nil {
		return big.NewInt(0)
	}
	
	// 获取点的字节表示并转换为big.Int
	data, err := p.MarshalBinary()
	if err != nil {
		return big.NewInt(0)
	}
	
	// 取前32字节转换为big.Int
	if len(data) > 32 {
		data = data[:32]
	}
	
	result := big.NewInt(0)
	result.SetBytes(data)
	return result
}

// scalarToBigInt 将kyber Scalar转换为big.Int
func scalarToBigInt(s kyber.Scalar) *big.Int {
	if s == nil {
		return big.NewInt(0)
	}
	
	data, err := s.MarshalBinary()
	if err != nil {
		return big.NewInt(0)
	}
	
	result := big.NewInt(0)
	result.SetBytes(data)
	return result
}
